package com.example.sams.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.sams.domain.enums.CourseReviewsStatus;
import com.example.sams.domain.enums.CourseStatus;
import com.example.sams.domain.po.*;
import com.example.sams.domain.request.ReviewCourseRequest;
import com.example.sams.domain.vo.CourseApplicationVO;
import com.example.sams.mapper.CourseReviewsMapper;
import com.example.sams.mapper.TeachersMapper;
import com.example.sams.service.ICourseReviewsService;
import com.example.sams.service.ICoursesService;
import com.example.sams.service.IUsersService;
import com.example.sams.utils.ResultUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 课程审核表 服务实现类
 * </p>
 *
 * @author jinghong
 * @since 2025-11-04
 */
@Service
public class CourseReviewsServiceImpl extends ServiceImpl<CourseReviewsMapper, CourseReviews> implements ICourseReviewsService {

    @Autowired
    private ICoursesService coursesService;

    @Autowired
    private TeachersMapper teachersMapper;

    @Autowired
    private IUsersService usersService;

    @Override
    public ResultUtil getCourseApplications(CourseStatus status) {
        // 1. 查询课程列表
        LambdaQueryWrapper<Courses> courseWrapper = new LambdaQueryWrapper<>();
        if (status != null) {
            courseWrapper.eq(Courses::getStatus, status);
        }
        List<Courses> courses = coursesService.list(courseWrapper);

        // 2. 构建课程申请VO列表
        List<CourseApplicationVO> applicationVOList = new ArrayList<>();
        for (Courses course : courses) {
            // 查询教师信息
            String teacherName = "未知教师";
            String teacherAccount = "";
            if (course.getTeacherId() != null) {
                Teachers teacher = teachersMapper.selectById(course.getTeacherId());
                if (teacher != null) {
                    Users teacherUser = usersService.getById(teacher.getUserId());
                    if (teacherUser != null) {
                        teacherName = teacherUser.getName();
                        teacherAccount = teacher.getAccount();
                    }
                }
            }

            CourseApplicationVO applicationVO = CourseApplicationVO.builder()
                    .id(course.getId())
                    .name(course.getName())
                    .teacherName(teacherName)
                    .teacherAccount(teacherAccount)
                    .credit(course.getCredit())
                    .capacity(course.getCapacity())
                    .status(course.getStatus())
                    .applyDate(course.getApplyDate())
                    .build();

            applicationVOList.add(applicationVO);
        }

        return ResultUtil.success(applicationVOList);
    }

    @Override
    @Transactional
    public ResultUtil reviewCourseApplication(String applicationId, String adminId, ReviewCourseRequest request) {
        // 1. 查询课程
        Courses course = coursesService.getById(applicationId);
        if (course == null) {
            return ResultUtil.error("课程不存在");
        }

        // 2. 验证审核状态
        CourseReviewsStatus reviewStatus = request.getStatus();
        if (reviewStatus == null) {
            return ResultUtil.error("审核状态不能为空");
        }

        // 3. 更新课程状态
        if (reviewStatus == CourseReviewsStatus.approved) {
            course.setStatus(CourseStatus.approved);
        } else if (reviewStatus == CourseReviewsStatus.rejected) {
            course.setStatus(CourseStatus.rejected);
        }
        boolean updated = coursesService.updateById(course);
        if (!updated) {
            return ResultUtil.error("更新课程状态失败");
        }

        // 4. 创建或更新审核记录
        LambdaQueryWrapper<CourseReviews> reviewWrapper = new LambdaQueryWrapper<>();
        reviewWrapper.eq(CourseReviews::getCourseId, applicationId);
        CourseReviews existingReview = this.getOne(reviewWrapper);

        if (existingReview != null) {
            // 更新现有审核记录
            existingReview.setReviewerId(adminId);
            existingReview.setStatus(reviewStatus);
            existingReview.setReason(request.getReason());
            existingReview.setReviewedAt(LocalDateTime.now());
            this.updateById(existingReview);
        } else {
            // 创建新审核记录
            CourseReviews courseReview = new CourseReviews();
            courseReview.setCourseId(applicationId);
            courseReview.setReviewerId(adminId);
            courseReview.setStatus(reviewStatus);
            courseReview.setReason(request.getReason());
            courseReview.setReviewedAt(LocalDateTime.now());
            this.save(courseReview);
        }

        // 5. 构建返回数据
        HashMap<String, Object> data = new HashMap<>();
        data.put("id", course.getId());
        data.put("status", course.getStatus().toString());

        // 6. 返回结果
        return ResultUtil.success("审核完成", data);
    }
}
